/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bitetorrent.helper;

import bitetorrent.model.AddressPort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author user
 */
public class Response extends HashMap<String, String> {

    String response;
    public ArrayList<AddressPort> peers;

    public Response(String response) throws Exception {
        this.response = response;
        peers = new ArrayList<AddressPort>();
        if (response == null) {
            throw new Exception("response null");
        } else {
            init();
        }
    }

    /**
     * I.S. : response not null
     */
    private void init() {
        String[] strings = response.split(";");
        String[] temp;
        String val;
        int i = 0;
        int length = strings.length;

        for (; i < length; ++i) {
            temp = strings[i].split(" ", 2);
            if (temp != null && temp[0] != null) {
                val = (temp.length < 2) ? "" : temp[1];
                put(temp[0], val);
            }
        }

        setPeers();
    }

    @Override
    public String toString() {
        Set<String> set = keySet();
        Iterator<String> iter = set.iterator();
        String str;
        String result = "";

        while (iter.hasNext()) {
            str = iter.next();
            result += str + " : " + get(str) + "\n";
        }

        return result;
    }

    private void setPeers() {
        String strPeers = get("peers");
        String[] arr;

        if (strPeers != null && strPeers.length() > 0) {
            // Remove spaces in last
            strPeers = strPeers.substring(0, strPeers.length() - 1);
            System.out.println("peers : " + strPeers);

            // Split
            arr = strPeers.split(" ");

            // Add to arraylist peers
            for (int i = 0; i < arr.length; ++i) {
                System.out.println("peer " + i + " : " + arr[i]);
                String[] split = arr[i].split(":");
                peers.add(new AddressPort(split[0], split[1]));
            }
        }
    }
}
